<?php
/**
 * @file Userm.php
 * @synopsis  用户操作
 * @author Yee, <rlk002@gmail.com>
 * @version 1.0
 * @date 2015-03-09 10:09:59
 */

defined('BASEPATH') OR exit('No direct script access allowed');

class Walletm extends CI_Model
{
    const TBL_RED_PACKET = 'qb_red_packet';

    const CK_RED_PACKET = 'red_packet_';

    const RP_TYPE_UNDEFINED = 0;            // 未定义
    const RP_TYPE_PERSONAL = 1;             // 个人红包, 指定用户
    const RP_TYPE_GROUP_LUCK = 2;           // 群拼手气红包
    const RP_TYPE_GROUP_NORMAL = 3;         // 群定额红包

    const RP_PAGE_TYPE_TIPS = 1;            // 红包文字信息页面
    const RP_PAGE_TYPE_2_UNFOLD = 2;        // 红包待拆开页面
    const RP_PAGE_TYPE_DETAIL = 3;          // 红包领取详情页面


    function __construct()
    {
        parent::__construct();
    }

    public function get_user_wallet_balance($user_id)
    {
        $filters = array('uid' => $user_id);
        $balance = $this->db->select('balance')->from('qb_user_wallet')->where($filters)->get()->row_array();
        if (empty($balance['balance'])) {
            return '0';
        }
        return $balance['balance'];
    }

    /**
     * 用户账单
     * @param $user_id
     * @param $start
     * @param $per_page
     */
    public function get_user_wallet_detail($user_id,$start,$per_page)
    {
       $detail = $this->db->select('a.amount,a.cmmnt,b.channel,a.uid,b.op_user,b.affect_user,b.receipt,b.receipt_type,a.addtime')
                          ->from('qb_user_wallet_history as a ')
                          ->join('qb_user_trade as b','a.trade_id=b.trade_id')
                          ->where('uid',$user_id)
                          ->order_by('whid','desc')
                          ->limit($per_page,$start)
                          ->get()->result_array();
        return $detail;

    }


    public function getUserThirdAccountID($uid, $account_type, $account_name, $account_email)
    {
        $whe = array('uid'=>$uid, 'account_type'=>$account_type, 'name'=>$account_name, 'email'=>$account_email);
        $query = $this->db->select('qbaid')->where($whe)->get('qb_user_relate_account', 1);
        $data = null;
        if ($query) {
            $data = $query->row_array();
        }

        if (isset($data['qbaid'])) {
            return $data['qbaid'];
        }
        else {
            $whe['addtime'] = time();
            $this->db->insert('qb_user_relate_account', $whe);
            return $this->db->insert_id();
        }
    }


    public function getUserThirdAccountByID($qbaid)
    {
        $query = $this->db->select('qbaid,uid,account_type,name,email,addtime')->where('qbaid', $qbaid)->get('qb_user_relate_account', 1);
        $data = null;
        if ($query) {
            $data = $query->row_array();
        }
        return $data;
    }


    public function genRedPacketID($uid, $amount_total, $count_total, $rptype, $luck_word, $gid, $receiver = 0)
    {
        $logstr = "genRedPacketID uid:{$uid}|amount_total:{$amount_total}|count_total:{$count_total}|rptype:{$rptype}|luck_word:{$luck_word}|gid:{$gid}|receiver:{$receiver}|" ;

        $new_data = array(
            'uid' => $uid,
            'amount_total' => $amount_total,
            'count_total' => $count_total,
            'rptype' => $rptype,
            'luck_word' => $luck_word,
            'gid' => $gid,
            'receiver' => $receiver,
        );

        $this->db->select('rpid,uid,amount_total,count_total,rptype,luck_word,gid,receiver');
        $this->db->where(['uid' => $uid, 'expiretime' => 0]);
        $query = $this->db->get(self::TBL_RED_PACKET, 1);
        if ($query) {
            $data = $query->row_array();
            if (isset($data['rpid'])) {
                $rpid = $data['rpid'];
                unset($data['rpid']);

                # 新旧数据对比
                if ($new_data != $data) {
                    $new_data['addtime'] = time();
                    $new_data['count_left'] = $count_total;
                    $new_data['amount_left'] = $amount_total;
                    $this->db->update(self::TBL_RED_PACKET, $new_data, ['rpid' => $rpid]);
                }
                w_log($logstr . "_1_update|rpid:{$rpid}");
                return $rpid;
            }
        }

        $new_data['addtime'] = time();
        $new_data['count_left'] = $count_total;
        $this->db->insert(self::TBL_RED_PACKET, $new_data);
        $rpid = $this->db->insert_id();

        w_log($logstr . "_2_insert|rpid:{$rpid}");
        return $rpid;
    }


    public function getRedPacketInfoByID($rpid, $no_cache = 0)
    {
        if (empty($rpid)) {
            return null;
        }
        ci_load_once('cache', 'mc');

        $key = self::CK_RED_PACKET . $rpid;
        $data = $no_cache ? null : $this->mc->get($key);
        if (empty($data)) {
            $this->db->load_balance_on();
            $this->db->where('rpid', $rpid);
            $query = $this->db->get(self::TBL_RED_PACKET, 1);
            $this->db->load_balance_off();
            if ($query) {
                $data = $query->row_array();

                if ($data['count_left'] == 0 && empty($rpinfo['finishtime'])) {
                    // 按时间倒序的接收者信息列表
                    $items = $this->tradem->get_red_wallet_group_userInfo($rpid);

                    $set = array('finishtime' => $items[0]['utime']);
                    if ($data['rptype'] == self::RP_TYPE_GROUP_LUCK && empty($data['refundtime'])) {
                        $winner = $winner_amount = 0;
                        foreach ($items as $item) {
                            if ($item['amount'] >= $winner_amount) {
                                $winner = $item['affect_user'];
                                $winner_amount = $item['amount'];
                            }
                        }
                        if ($winner) {
                            $set['winner'] = $winner;
                        }
                    }

                    $this->db->update(self::TBL_RED_PACKET, $set, ['rpid'=>$rpid]);
                    $data = array_merge($data, $set);

                    // 红包抢完加缓存
                    $this->mc->save($key, $data, Tradem::CACHE_RED_PACKET);
                }
            }
        }
        return $data;
    }


    // 生成红包金额
    public function allotRandomRedPacketAmount($red_packet_info)
    {
        if ($red_packet_info['count_left'] == 1) {
            return $red_packet_info['amount_left'];
        }

        if ($red_packet_info['rptype'] == self::RP_TYPE_GROUP_LUCK) {
            // 随机算法, 模仿微信
            $safe_total = ($red_packet_info['amount_left'] - $red_packet_info['count_left'] + 1) / ($red_packet_info['count_left'] - 1);  //随机安全上限
            $amount = mt_rand(1, $safe_total);
        }
        else {
            $amount = $red_packet_info['amount_left'] / $red_packet_info['count_left'];  // 均分
            $amount = intval($amount);
        }
        return $amount;
    }



    public function getDayWalletConsuming($user_id)
    {
        ci_load_once('tradem');
        $zero = strtotime('today');
        $this->db->select_sum('a.amount');
        $this->db->from(Tradem::TBL_USER_ACCOUNT_HISTORY . ' a');
        $this->db->join(Tradem::TBL_TRADE . ' b', 'a.trade_id = b.trade_id', 'left');
        $this->db->where('a.amount<', 0);
        $this->db->where('a.uid', $user_id);
        $this->db->where('a.addtime>=', $zero);
        $this->db->where('a.addtime<=', $zero + 24 * 60 * 60);
        $this->db->where('b.pay_method', Tradem::PAYMENT_WALLET);

        $data = $this->db->get()->row_array();

        // 支出金额是负数
        return abs($data['amount']);
    }


    public function validateRedPacket($rptype, $amount_total, $count_total)
    {
        if (! $count_total) {
            return '红包个数有误';
        }
        if (1 > $amount_total || ($count_total > $amount_total)) {
            return '单个红包金额不可低于0.01元，请重新填写';
        }
        elseif ($count_total * 20000 < $amount_total ) {
            return '单个红包金额不可超过200元，请重新输入';
        }
        if (($rptype == self::RP_TYPE_PERSONAL && $count_total != 1)
            || ($rptype == self::RP_TYPE_GROUP_LUCK && $count_total < 1)
            || ($rptype == self::RP_TYPE_GROUP_NORMAL && $count_total < 1)
        ) {
            return '红包个数有误';
        }
        if (($rptype == self::RP_TYPE_GROUP_LUCK && $count_total > 100)
            || ($rptype == self::RP_TYPE_GROUP_NORMAL && $count_total > 100)
        ) {
            return '一次最多发100个红包';
        }

        return '';
    }
}
